import 'dart:io';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/module/mine/my_page_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/base/wqs_image.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final logic = Get.put(MyPageLogic());
  final visibleKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    final s = AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(statusBarBrightness: Brightness.dark),
      child: GetBuilder<MyPageLogic>(builder: (logic) {
        return VisibilityDetector(
          key: const Key("my"),
          onVisibilityChanged: (VisibilityInfo info) async {
            if (!info.visibleBounds.isEmpty && User.isLogin) {
              logic.coupons = await PayApi.myCoupons() ?? [];
            }
          },
          child: LoadingWidget<bool>(
            isLoading: false,
            data: false,
            reconnect: logic.getRefresh,
            child: () => Scaffold(
              backgroundColor: Colours.N1,
              extendBodyBehindAppBar: true,
              appBar: Styles.appBar(
                  backgroundColor: Colours.transparent, showLeading: false),
              body: EasyRefresh.builder(
                controller: logic.refreshC,
                onRefresh: () async {
                  logic.onRefresh = true;
                  await User.fetchUserInfo();
                  if (User.isLogin) {
                    logic.coupons = await PayApi.myCoupons() ?? [];
                  }
                  update();
                  logic.onRefresh = false;
                },
                childBuilder: (context, physics) => Column(
                  children: [
                    Expanded(
                      child: SingleChildScrollView(
                          physics: physics,
                          child: Stack(
                            children: [
                              Container(
                                height: 310, //使用比head略高的高度
                                decoration: const BoxDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment.centerLeft,
                                    end: Alignment.centerRight,
                                    colors: [
                                      Color(0xFF9DCFFF),
                                      Color(0xFFD2E7FF),
                                      Color(0xFFCEE8FF)
                                    ],
                                  ),
                                ),
                              ),
                              Image.asset(Utils.getImgPath("my_header_bg.png"),
                                  fit: BoxFit.cover),
                              Column(
                                children: [
                                  header(),
                                  settingList(),
                                ],
                              ),
                            ],
                          )),
                    ),
                    body(),
                  ],
                ),
              ),
            ),
          ),
        );
      }),
    );
    return VisibilityDetector(
        key: visibleKey,
        child: s,
        onVisibilityChanged: (info) {
          if (!info.visibleBounds.isEmpty) {
            SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
                statusBarBrightness: Brightness.dark,
                statusBarIconBrightness: Brightness.dark));
            update();
          }
        });
  }

  Widget body() {
    return GetBuilder<MyPageLogic>(builder: (logic) {
      double availableHeight = MediaQuery.of(context).size.height -
          AppBar().preferredSize.height - // 减去AppBar的高度
          MediaQuery.of(context).padding.top -
          MediaQuery.of(context).padding.bottom;
      // print("availableHeight: $availableHeight");
      // 判断当前可用高度是否足够
      EdgeInsets padding = availableHeight > 580
          ? EdgeInsets.only(bottom: Utils.dp(14, context))
          : EdgeInsets.only(bottom: Utils.dp(2, context));
      return Container(
          alignment: Alignment.bottomCenter,
          padding: padding,
          child: User.isLogin
              ? QsButton(
                  onPressed: () async {
                    final value = await WidgetUtils.alertQuery("确定退出登录吗？");
                    if (value == true) {
                      await User.doLogRefresh(isLogin: false);
                      update();
                    }
                  },
                  height: 48,
                  width: Get.width - 40,
                  text: "退出登录",
                  textStyle: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w500),
                  borderRadius: 24,
                  borderSide: const BorderSide(color: Colours.B6, width: 0.5),
                  foregroundColor: Colours.B6,
                  backgroundColor: Colours.B1,
                )
              : Container());
    });
  }

  Widget avatar() => Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Container(
            width: 130,
            height: 130,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white,
                width: 5,
              ),
            ),
            child: QsImage(
              imageUrl: User.info?.avatar ?? "",
              fit: BoxFit.cover,
              shape: BoxShape.circle,
              width: 120,
              height: 120,
              errorWidget: Image.asset(Utils.getImgPath("my_person.png")),
            ),
          )
        ],
      );

  Widget loginBtn() => Container(
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              QsText(
                User.isLogin ? (User.info?.name ?? '') : "登录/注册",
                color: User.info?.isVip == 1
                    ? const Color(0xFF733305)
                    : Colours.text,
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
              if (User.info?.isVip == 1)
                Image.asset(Utils.getImgPath("user_vip_label.png"), width: 68)
                    .paddingOnly(left: 8)
            ],
          ),
          if (User.info?.isVip == 1)
            QsText("到期时间：${DateTime.tryParse(User.info?.vipEndTime ?? "")?.formatedString("yyyy年MM月dd日")}",
                    fontSize: 12, color: Colours.grey99)
                .paddingOnly(top: 2)
        ],
      ));

  Widget header() => SizedBox(
      height: 262, // 设置高度为262
      child: Stack(
        children: [
          Column(
              mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
              crossAxisAlignment: CrossAxisAlignment.center, // 水平居中
              children: [
                const SizedBox(height: 70),
                avatar(),
                const SizedBox(height: 8),
                loginBtn(),
                // const SizedBox(height: 14),
              ]).tap(logic.tapHeaderName),
        ],
      ));

  Widget settingList() => Container(
        decoration: BoxDecoration(
          color: Colours.N1,
          borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
        ),
        padding: const EdgeInsets.symmetric(vertical: 12),
        child: Column(
          children: [
            //cell("my_icon_edit.png", "编辑资料").tap(logic.tapUserInfo),
            cell("my_icon_contact.png", "联系客服").tap(logic.tapContact),
            cell("my_icon_settings.png", "更多设置").tap(logic.tapSettings),
            cell("my_icon_about.png", "关于我们").tap(logic.tapAboutUs),
          ],
        ),
      );

  Widget cell(String image, String text,
          {String right = "", bool showArrow = true, double? size}) =>
      Container(
        padding: const EdgeInsets.symmetric(horizontal: 18),
        height: 50,
        child: Row(
          children: [
            Image.asset(Utils.getImgPath(image),
                width: size ?? 18, height: size ?? 18),
            const SizedBox(width: 8),
            QsText(text, fontSize: 14, color: Colours.N9),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Flexible(
                    child: QsText(right,
                            textAlign: TextAlign.right,
                            maxLines: 2,
                            fontSize: 14,
                            color: Colours.N8)
                        .marginSymmetric(horizontal: 8),
                  ),
                ],
              ),
            ),
            Image.asset(Utils.getImgPath("icon_arrow_right.png"),
                width: 6, height: 10)
          ],
        ),
      );
}
